package is.ru.honn.rumblr.factory;

import is.ru.honn.rumblr.domain.AbstractRumblrPost;
import is.ru.honn.rumblr.domain.RumblrPost;
import is.ru.honn.rumblr.domain.RumblrType;
import is.ru.honn.rumblr.util.RumblerLog;
import is.ru.honn.rumblr.util.XmlUtil;
import org.dom4j.Element;

import java.text.ParseException;
import java.util.Date;
import java.util.logging.Logger;

abstract public class PostFactory
{
  abstract public RumblrPost createPostFromXML(Element e);

  public static RumblrPost createPost(Element e) throws FactoryException
  {
    String xmlType = XmlUtil.getXPathValue(e, "@type");
    RumblrType type = RumblrType.fromString(xmlType);
    RumblrPost post = null;

    try
    {
      Class<? extends PostFactory> c = type.getFactory();
      PostFactory factory = (PostFactory) c.newInstance();

      post = factory.createPostFromXML(e);
    }
    catch (Exception ex)
    {
      String msg = "Unable to create new type '" + xmlType + "'";
      Logger.getLogger(RumblerLog.LOG_NAME).severe(msg);
      throw new FactoryException(ex);
    }
    return post;
  }

  public static PostFactory getFactory(String typename) throws FactoryException
  {
    RumblrType type = RumblrType.fromString(typename);
    PostFactory factory;
    try
    {
      Class<? extends PostFactory> c = type.getFactory();
      factory = (PostFactory)c.newInstance();
    }
    catch (Exception ex)
    {
      String msg = "Unable to create new type '" + typename + "'";
      Logger.getLogger(RumblerLog.LOG_NAME).severe(msg);
      throw new FactoryException(ex);
    }
    return factory;
  }

  public void createHeader(AbstractRumblrPost post, Element e)
  {
    post.setId(XmlUtil.getXPathValue(e, "@id"));
    post.setUrl(XmlUtil.getXPathValue(e, "@url"));
    post.setType(XmlUtil.getXPathValue(e, "@type"));
    try
    {
      post.setDateGmt(XmlUtil.getXPathValueAsDate(e, "@date-gmt"));
    }
    catch (ParseException e1)
    {
      post.setDateGmt(new Date());
    }

    post.addTags(XmlUtil.getMultipleValues(e, "tag"));
  }
}
